<template>
  <el-card>
    <el-form label-width="120px" :model="formData" :rules="formRules" ref="addForm">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select @change="firstCateChange" v-model="formData.first_cateid">
              <el-option label="请选择" value></el-option>
              <el-option
                v-for="item in firstCates"
                :key="item.id"
                :label="item.catename"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select v-model="formData.second_cateid">
              <el-option label="请选择" value></el-option>
              <el-option
                v-for="item in secondCates"
                :key="item.id"
                :label="item.catename"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品名称" prop="goodsname">
            <el-input placeholder="商品名称" v-model="formData.goodsname"></el-input>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input placeholder="商品价格" v-model="formData.price"></el-input>
          </el-form-item>

          <el-form-item label="市场价格" prop="market_price">
            <el-input placeholder="市场价格" v-model="formData.market_price"></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :auto-upload="false"
              class="upload-demo"
              :file-list="fileList"
              :limit="1"
              :on-change="fileChange"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>

          <el-form-item label="商品规格" prop="specsid">
            <el-select v-model="formData.specsid" @change="specsChange">
              <el-option label="请选择" value></el-option>
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :label="item.specsname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="规格属性值" prop="specsattr">
            <el-select v-model="formData.specsattr" multiple>
              <el-option label="请选择" value></el-option>
              <el-option
                v-for="(item,index) in specsAttrList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否新品" prop="isnew">
            <el-radio-group v-model="formData.isnew">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否热卖" prop="ishot">
            <el-radio-group v-model="formData.ishot">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="详细信息" name="second">
          <vue-wangeditor id="wangeditor" ref="wangeditor" v-model="formData.description" width="100%"></vue-wangeditor>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button type="primary" @click="submitForm('addForm')">立即修改</el-button>
        <el-button type="primary">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import Vue from "vue";
import vueWangeditor from "vue-wangeditor";
export default {
  components: {
    vueWangeditor
  },
  data() {
    return {
      // 图片上传组件
      fileList: [], // 上传文件列表
      dialogImageUrl: "",
      dialogVisible: false,
      activeName: "first",
      firstCates: [],
      secondCates: [],
      formData: {
        id: this.$route.params.id,
        first_cateid: "", // 一级分类
        second_cateid: "", // 二级分类
        goodsname: "", // 商品名称
        price: "", //销售价格
        market_price: "", //市场价格
        description: "", //商品详情
        specsid: "", //属性名id
        specsattr: [], //属性值
        isnew: 0, //是否新品
        ishot: 0, // 是否热门
        img: "", // 商品图片
        status: 1, // 商品状态
        description:''
      },
      // 商品规格列表
      specsList: [],
      //  规格属性值
      specsAttrList: [],
      //   表单校验规则
      formRules: {
        first_cateid: {
          required: true,
          message: "请选择一级分类",
          trigger: "blur"
        },
        second_cateid: {
          required: true,
          message: "请选择二级分类",
          trigger: "blur"
        },
        goodsname: {
          required: true,
          message: "请输入商品名称",
          trigger: "blur"
        },
        price: { required: true, message: "请输入商品价格", trigger: "blur" },
        market_price: {
          required: true,
          message: "请输入市场价格",
          trigger: "blur"
        },
        specsid: { required: true, message: "请选择规格名称", trigger: "blur" },
        specsattr: {
          required: true,
          message: "请选择规格属性",
          trigger: "blur"
        },
        isnew: { required: true, message: "请选择", trigger: "blur" },
        ishot: { required: true, message: "请选择", trigger: "blur" },
        status: { required: true, message: "请选择", trigger: "blur" }
      }
    };
  },
  methods: {
    //  图片上传组件
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    fileChange(file) {
      // 将图片原始数据保存在数据模型中
      this.formData.img = file.raw;
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    // 监听一级分类的改变, 更新二级分类
    firstCateChange(id) {
      const index = this.firstCates.findIndex(item => item.id == id);
      this.secondCates = this.firstCates[index].children;
    },
    // 获取商品信息
    async getGoodsInfo() {
      const res = await this.$http.get(`/api/goodsinfo?id=${this.formData.id}`);
      if (res.code == 200) {
        this.formData = res.list;
        const index = this.firstCates.findIndex(
          item => item.id == res.list.first_cateid
        );
        this.secondCates = this.firstCates[index]["children"];
        // 处理规格值
        this.formData.specsattr = res.list.specsattr.split(",");
        // console.log(res.list.specsattr,'res.list.specsattr');
        // 原始图片预览
        this.fileList.push({
          name: res.list.goodsname,
          url: this.$imgBaseUrl + res.list.img
        });
        // 在富文本编辑器中展示商品详情
        this.$nextTick(() => {
          this.$refs["wangeditor"].setHtml(res.list.description);
        });
      }
    },
    // 获取分类
    async getCateList() {
      const res = await this.$http.get("/api/catelist?istree=1");
      if (res.code == 200) {
        this.firstCates = res.list;
      }
    },
    // 获取商品规格
    async getSpecs() {
      const res = await this.$http.get("/api/specslist");
      this.specsList = res.list;
    },
    // 监听规格更新
    async specsChange(id) {
      // 获取某个规格
      const res = await this.$http.get(`/api/specsinfo?id=${id}`);
      this.specsAttrList = res.list[0].attrs;
      // 清空原始的规格属性
      this.formData.specsattr = "";
    },
    // 提交表单
    submitForm(form) {
      this.$refs[form].validate(async valid => {
        if (valid) {
          // 由于存在图片文件, 所以必须使用FormData的方式进行数据提交
          // 获取富文本的内容
          // this.formData.description = this.$refs["wangeditor"].getHtml();
          const fd = new FormData();
          for (let key in this.formData) {
            fd.append(key, this.formData[key]);
          }
          fd.append("id", this.$route.params.id);
          fd.append("specsattr", this.formData.specsattr.join(","));
          const res = await this.$http.post("/api/goodsedit", fd);
          if(res.code==200){
            this.$success('操作成功');
          }else{
            this.$error('操作失败');
          }
        } else {
          console.log("fail");
        }
      });
    }
  },
  created() {
    this.getCateList();
    this.getGoodsInfo();
    this.getSpecs();
  }
};
</script>

<style scoped>
.el-input {
  width: 600px;
}
</style>